package com.iwhalecloud.bss.kite.cucc.web.service.accept.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosGoodsDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosProductDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;


import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
import java.util.stream.Collectors;


public class ConnectProdUtil {

    /**
     * 通过变更单接口获取指定号码下的通信计划和资费计划标识
     * @param custId
     * @param serialNumber
     * @return
     */
    public static Map<String, Object> getPlanNbrsByAccNum(String custId, String serialNumber) {
        List<String> communicationPlanNbrs = new ArrayList<>();
        List<String> tariffPlanNbrs = new ArrayList<>();
        IOrderService orderService = SpringUtil.getBean(IOrderService.class);

        String provinceId = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        String lanId = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");

        Map<String, Object> orderInfo = orderService.getChangeOriginOrder("", custId, serialNumber, provinceId, lanId, staffCode, "");
        KitePosDTO kitePosDTO = JSONObject.toJavaObject(JSON.parseObject(JSON.toJSONString(orderInfo)), KitePosDTO.class);
        List<KitePosGoodsDTO> posGoods = kitePosDTO.getGoods();

        if (KiteListUtils.isNotEmpty(posGoods)) {
            posGoods = posGoods.stream().filter(offerInst -> !GoodsInfoTransfer.isAddRoleOffer(offerInst.getCode(), offerInst.getCatagoryId())).collect(Collectors.toList());
            if (KiteListUtils.isNotEmpty(posGoods)) {
                for (KitePosGoodsDTO goods : posGoods) {
                    List<KitePosProductDTO> products = goods.getProducts().stream()
                        .filter(dto -> LocalKeyConsts.PRODUCT_TYPE_BASE.equals(dto.getType())).collect(Collectors.toList());
                    products.forEach(product ->{
                        // 通信计划
                        communicationPlanNbrs.addAll(listCommunicationPlanNbrsByAccNum(product, "200003687"));
                        // 资费计划
                        tariffPlanNbrs.addAll(listTariffPlanNbrsByAccNum(product,"200003698"));
                    });
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("tx_plan", communicationPlanNbrs);
        result.put("zf_plan", tariffPlanNbrs);
        return result;
    }

    /**
     * 获取product节点下的通信计划标识
     * @param product
     * @param attrCode
     * @return
     */
    public static List<String> listCommunicationPlanNbrsByAccNum(KitePosProductDTO product, String attrCode) {
        List<String> list = new ArrayList<>();

        List<KitePosAttrDTO> attrGroups = product.getAttrs().stream().
            filter(attr -> "ATTR_GROUP".equals(attr.getType()) && ("300000151".equals(attr.getCode()) || LocalKeyConsts.FUNC_PROD_ID_YF5GTX.equals(attr.getCode()))).collect(Collectors.toList());
        for (KitePosAttrDTO attrGroup : attrGroups) {
            String attrValue = attrGroup.getValue();
            Map<String, Object> attrValueMap = JSONObject.parseObject(attrValue, Map.class);

            Iterator<String> it = attrValueMap.keySet().iterator();
            while (it.hasNext()) {
                JSONArray attrListValue = (JSONArray) attrValueMap.get(it.next());
                List<KitePosAttrDTO> prodInstAttrs = JSONArray.parseArray(JSONArray.toJSONString(attrListValue), KitePosAttrDTO.class);

                String finalAttrCode = attrCode==null ? "200004128":attrCode;

                KitePosAttrDTO kitePosAttrDTO = prodInstAttrs.stream().filter(attr -> finalAttrCode.equals(attr.getCode())).findFirst().orElse(null);
                if (Objects.nonNull(kitePosAttrDTO) && KiteStringUtils.isNotEmpty(kitePosAttrDTO.getValue())) {
                     list.add(kitePosAttrDTO.getValue());
                }
            }
        }

        return list;
    }

    /**
     * 获取product节点下的资费计划标识
     * @param product
     * @return
     */
    public static List<String> listTariffPlanNbrsByAccNum(KitePosProductDTO product, String attrCode) {
        List<String> list = new ArrayList<>();

        List<KitePosAttrDTO> attrGroups = product.getAttrs().stream().
            filter(attr -> "ATTR_GROUP".equals(attr.getType()) && "300000152".equals(attr.getCode())).collect(Collectors.toList());
        if (KiteListUtils.isEmpty(attrGroups)) {
            attrGroups = product.getAttrs().stream().
                filter(attr -> "ATTR_GROUP".equals(attr.getType()) && ("300000170".equals(attr.getCode()) || LocalKeyConsts.FUNC_PROD_ID_YF5GZF_BASE.equals(attr.getCode()))).collect(Collectors.toList());
        }
        for (KitePosAttrDTO attrGroup : attrGroups) {
            String attrValue = attrGroup.getValue();
            Map<String, Object> attrValueMap = JSONObject.parseObject(attrValue, Map.class);

            Iterator<String> it = attrValueMap.keySet().iterator();
            while (it.hasNext()) {
                JSONArray attrListValue = (JSONArray) attrValueMap.get(it.next());
                List<KitePosAttrDTO> prodInstAttrs = JSONArray.parseArray(JSONArray.toJSONString(attrListValue), KitePosAttrDTO.class);
                String finalAttrCode = attrCode==null ? "200004129":attrCode;
                KitePosAttrDTO kitePosAttrDTO = prodInstAttrs.stream().filter(attr -> finalAttrCode.equals(attr.getCode())).findFirst().orElse(null);
                if (Objects.nonNull(kitePosAttrDTO) && KiteStringUtils.isNotEmpty(kitePosAttrDTO.getValue())) {
                    list.add(kitePosAttrDTO.getValue());
                }
            }
        }
        return list;
    }

    /**
     * 通过变更单接口获取指定号码下的通信计划名称
     * @param custId
     * @param serialNumber
     * @return
     */
    public static Map<String, Object> getPlanNanmesByAccNum(String custId, String serialNumber) {
        List<String> communicationPlanNbrs = new ArrayList<>();
        List<String> tariffPlanNbrs = new ArrayList<>();
        IOrderService orderService = SpringUtil.getBean(IOrderService.class);

        String provinceId = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        String lanId = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");

        Map<String, Object> orderInfo = orderService.getChangeOriginOrder("", custId, serialNumber, provinceId, lanId, staffCode, "");
        KitePosDTO kitePosDTO = JSONObject.toJavaObject(JSON.parseObject(JSON.toJSONString(orderInfo)), KitePosDTO.class);
        List<KitePosGoodsDTO> posGoods = kitePosDTO.getGoods();

        if (KiteListUtils.isNotEmpty(posGoods)) {
            posGoods = posGoods.stream().filter(offerInst -> !GoodsInfoTransfer.isAddRoleOffer(offerInst.getCode(), offerInst.getCatagoryId())).collect(Collectors.toList());
            if (KiteListUtils.isNotEmpty(posGoods)) {
                for (KitePosGoodsDTO goods : posGoods) {
                    List<KitePosProductDTO> products = goods.getProducts().stream()
                        .filter(dto -> LocalKeyConsts.PRODUCT_TYPE_BASE.equals(dto.getType())).collect(Collectors.toList());
                    products.forEach(product ->{
                        // 通信计划
                        communicationPlanNbrs.addAll(listCommunicationPlanNbrsByAccNum(product, "200003687"));
                    });
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("tx_plan", communicationPlanNbrs);
        return result;
    }

}
